"use strict";

let _jsonData = null;
let _rcbEditor = null;
let _wlEditor = null;
let _lineWrapping = false;

function loadData() {
	chrome.runtime.sendMessage({name: "get-data"}, function(result) {
		const cursor = _rcbEditor.getCursor();
		const scroll = _rcbEditor.getScrollInfo();

		let jsonStr = JSON.stringify(result.rootJson, undefined, 2);
		_rcbEditor.setValue(jsonStr);

		_rcbEditor.setCursor(cursor);
		_rcbEditor.scrollTo(scroll.left, scroll.top);
		_rcbEditor.focus();
	});
}

function loadWhiteList() {
	chrome.runtime.sendMessage({name: "get-whitelist"}, function(result) {
		const cursor = _wlEditor.getCursor();
		const scroll = _wlEditor.getScrollInfo();

		_wlEditor.setValue(result.whitelist);
		_wlEditor.refresh();

		_wlEditor.setCursor(cursor);
		_wlEditor.scrollTo(scroll.left, scroll.top);
		_wlEditor.focus();
	});
}

function updateDescription() {
	_jsonData.description = $("#email-description").val();
	$("#email-code").text(JSON.stringify(_jsonData, undefined, 2));
}

function loadEmail() {
	chrome.storage.local.get("capture", function(data) {
		if (!data.capture) {
			if ($("body").attr("data-tab") === "sendemail") {
				$("body").attr("data-tab", "data");
				resizeCodeMirror();
			}
			$("select#sendemail-class").attr("selectedIndex", "0");
			$("#tab-sendemail").css("display", "none");
		} else {
			_jsonData = data.capture.jsonData;
			_jsonData.platform = "网站网页";
			updateDescription();
			$("body").attr("data-tab", "sendemail");
			$("#tab-sendemail").css("display", "");
			$("#email-screenshot").attr("src", "data:" + data.capture.imageData);
		}
	});
}

function loadOptions() {
	chrome.storage.local.get({
			performance_mode: true, 
			editor_line_wrapping: false, 
			dynamic_filter_level: 0, 
			enable_src_cache: true,
			continue_selecting_mode: false,
	}, function(data) {
		$("#performance_mode").prop("checked", data.performance_mode);
		$("#editor_line_wrapping").prop("checked", data.editor_line_wrapping);
		$("#dynamic_filter_level").val(data.dynamic_filter_level);
		$("#enable_src_cache").prop("checked", data.enable_src_cache);
		$("#continue_selecting_mode").prop("checked", data.continue_selecting_mode);

		applyEditorOptions(data.editor_line_wrapping);
	});
}

function applyEditorOptions(editor_line_wrapping) {
	if (_rcbEditor !== null) {
		_rcbEditor.setOption("lineWrapping", editor_line_wrapping);
	}
	if (_wlEditor !== null) {
		_wlEditor.setOption("lineWrapping", editor_line_wrapping);
	}
}

function dataURItoBlob(dataURI) {
	let byteString = atob(dataURI.split(",")[1]);
	let mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
	let ab = new ArrayBuffer(byteString.length);
	let ia = new Uint8Array(ab);

	for (let i=0; i<byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}

	return new Blob([ab], {type: mimeString});
}

function getFormattedTime() {
	const now = new Date();

	const year = now.getFullYear();
	const month = ("0" + (now.getMonth() + 1)).slice(-2);
	const day = ("0" + now.getDate()).slice(-2);
	const hours = ("0" + now.getHours()).slice(-2);
	const minutes = ("0" + now.getMinutes()).slice(-2);
	const seconds = ("0" + now.getSeconds()).slice(-2);

	const formattedTime = year + month + day + hours + minutes + seconds;

	return formattedTime;
}

function resizeCodeMirror() {
	if (_rcbEditor !== null) {
		_rcbEditor.setSize($("#recyclebin-data-wrapper").width(), $("#recyclebin-data-wrapper").height());
		_rcbEditor.refresh();
	}
	if (_wlEditor !== null) {
		_wlEditor.setSize($("#whitelist-data-wrapper").width(), $("#whitelist-data-wrapper").height());
		_wlEditor.refresh();
	}
}

$(window).resize(resizeCodeMirror);

$(document).ready(function() {
	const keyBindings = {
		"Ctrl-F": "find",
		"F3": "findNext",
		"Shift-F3": "findPrev",
		"Ctrl-H": "replace",
		"Ctrl-Z": "undo",
		"Ctrl-Y": "redo",
		"Ctrl-A": "selectAll",
		"Ctrl-G": "jumpToLine",
		"Shift-Ctrl-F": "findPersistent"
	};

	_rcbEditor = CodeMirror.fromTextArea(document.getElementById("recyclebin-data"), {
		lineNumbers: true,
		extraKeys: keyBindings
	});

	_wlEditor = CodeMirror.fromTextArea(document.getElementById("whitelist-data"), {
		lineNumbers: true,
		extraKeys: keyBindings
	});

	resizeCodeMirror();

	chrome.storage.local.onChanged.addListener(function(changes) {
		if (changes.capture) {
			loadEmail();
		}
	});
	loadWhiteList();
	loadData();
	loadOptions();
	loadEmail();
	
	$.get(chrome.runtime.getURL("manifest.json"), function(info) {
		$("#recyclebin-title").text(" 回收站 v" + info.version);
	});
	
	$("#tab-data").click(function(event) {
		$("body").attr("data-tab", "data");
		resizeCodeMirror();
	});

	$("#tab-whitelist").click(function(event) {
		$("body").attr("data-tab", "whitelist");
		resizeCodeMirror();
	});

	$("#tab-options").click(function(event) {
		$("body").attr("data-tab", "options");
	});
	
	$("#tab-sendemail").click(function(event) {
		$("body").attr("data-tab", "sendemail");
	});
	
	$("#recyclebin-reload").click(function() {
		loadData();
	});
	
	$("#recyclebin-find").click(function() {
		_rcbEditor.execCommand("findPersistent");
	});

	$("#recyclebin-save").click(function() {
		let jsonStr = _rcbEditor.getValue();
		let jsonObj = (jsonStr.trim() == "") ? null : JSON.parse(jsonStr);
		chrome.runtime.sendMessage({name: "set-data", data: jsonObj});
	});
	
	$("#recyclebin-clear").click(function() {
		_rcbEditor.setValue("");
	});

	$("#recyclebin-backup").click(function() {
		let file = new File([_rcbEditor.getValue()], "回收站数据备份"+getFormattedTime()+".bak", {type: "text/plain;charset=utf-8"});
		saveAs(file);
	});

	$("#recyclebin-restore").click(function() {
		$("#fileInput").change(function() {
			if (this.files.length === 0) {
				return;
			}
			const reader = new FileReader();
			reader.onload = function fileReadCompleted() {
				_rcbEditor.setValue(reader.result);
				$("#recyclebin-save").click();
			}
			reader.readAsText(this.files[0], "utf-8");
		});
		$("#fileInput").click();
	});
	
	$("#whitelist-reload").click(function() {
		loadWhiteList();
	});

	$("#whitelist-find").click(function() {
		_wlEditor.execCommand("findPersistent");
	});
	
	$("#whitelist-save").click(function() {
		chrome.runtime.sendMessage({name: "set-whitelist", whitelist: _wlEditor.getValue()});
	});
	
	$("#whitelist-clear").click(function() {
		_wlEditor.setValue("");
	});
	
	$("#whitelist-backup").click(function() {
		let file = new File([_wlEditor.getValue()], "回收站白名单备份"+getFormattedTime()+".bak", {type: "text/plain;charset=utf-8"});
		saveAs(file);
	});

	$("#whitelist-restore").click(function() {
		$("#fileInput2").change(function() {
			if (this.files.length === 0) {
				return;
			}
			const reader = new FileReader();
			reader.onload = function fileReadCompleted() {
				_wlEditor.setValue(reader.result);
				$("#whitelist-save").click();
			}
			reader.readAsText(this.files[0], "utf-8");
		});
		$("#fileInput2").click();
	});

	$("#performance_mode").change(function() {
		chrome.storage.local.set({performance_mode: $(this).is(":checked")});
		chrome.runtime.sendMessage({name: "update-options"});
	});

	$("#continue_selecting_mode").change(function() {
		chrome.storage.local.set({continue_selecting_mode: $(this).is(":checked")});
		chrome.runtime.sendMessage({name: "update-options"});
	});

	$("#enable_src_cache").change(function() {
		chrome.storage.local.set({enable_src_cache: $(this).is(":checked")});
		chrome.runtime.sendMessage({name: "update-options"});
	});
	
	$("#editor_line_wrapping").change(function() {
		let checked = $(this).is(":checked");
		chrome.storage.local.set({editor_line_wrapping: checked});
		applyEditorOptions(checked);
	});
	
	$("#dynamic_filter_level").change(function() {
		chrome.storage.local.set({dynamic_filter_level: $(this).val()});
		chrome.runtime.sendMessage({name: "update-options"});
	});

	$("#recyclebin-exportreport").click(function() {
		let jsonStr = _rcbEditor.getValue();
		let jsonObj = (jsonStr.trim() == "") ? null : JSON.parse(jsonStr);
		let hostCount = {};
		for (let jsonItem of jsonObj.data) {
			let host = jsonItem.host;
			if (hostCount[host]) {
				hostCount[host]++;
			} else {
				hostCount[host] = 1;
			}
		}
		let report = "";
		let sortedKeys = Object.keys(hostCount).sort((key1, key2) => {
			return hostCount[key2] - hostCount[key1];
		});
		for (let key of sortedKeys) {
			report += key + " = " + hostCount[key] + "\n";
		}
		let file = new File([report], "回收站站点统计"+getFormattedTime()+".txt", {type: "text/plain;charset=utf-8"});
		saveAs(file);
	});
	
	$("#recyclebin-clearsite").click(function() {
		if ($("#recyclebin-clearsitediv").css("display") === "none") {
			$("#recyclebin-clearsite").val("隐藏删除站点");
			$("#recyclebin-clearsitediv").css("display", "inline");
		} else {
			$("#recyclebin-clearsite").val("删除站点数据");
			$("#recyclebin-clearsitediv").css("display", "none");
		}
	});
	
	$("#recyclebin-clearsiteok").click(function() {
		let jsonStr = _rcbEditor.getValue();
		let jsonObj = (jsonStr.trim() == "") ? null : JSON.parse(jsonStr);
		
		let sitetoclear = $("#recyclebin-sitetoclear").val();
		let arrdata = jsonObj.data;
		let i = arrdata.length - 1;
		let count = 0;
		while (i >= 0) {
			if (arrdata[i].host === sitetoclear) {
				arrdata.splice(i, 1);
				count++;
			}
			i--;
		}

		jsonStr = JSON.stringify(jsonObj, undefined, 2);
		_rcbEditor.setValue(jsonStr);
		alert("已删除" + count + "条站点数据,请根据需要保存或者备份.");
	});
	
	$("#sendemail-class").on("change", function() {
		$("#subject").text("我要举报: " + $("#sendemail-class").val());
	});

	$("#email-description").change(updateDescription);

	$("#email-description").on("input", updateDescription);

	function checkDescription() {
		let description = _jsonData.description;
		if (description == "") {
			alert("请填写举报描述!");
			$("#email-description").val("请输入举报内容描述(不能超过500个字符)").focus().select();
			updateDescription();
			return false;
		} else if (description === "请输入举报内容描述(不能超过500个字符)") {
			alert("请将举报描述修改为实际内容!");
			$("#email-description").focus().select();
			updateDescription();
			return false;
		}
		return true;
	}

	$("#sendemail-copy-send").click(function() {
		let subject = "我要举报: " + $("#sendemail-class").val();
		if (subject.indexOf("===") >= 0) {
			alert("请选择举报类别!");
			return;
		}

		if (!checkDescription()) {
			return;
		}
		
		try {
			// 复制图文内容;
			let node = document.getElementById("email-content");
			let sel = window.getSelection();
			sel.selectAllChildren(node);
			document.execCommand("copy");
		} catch (err) {
			// 复制文本内容;
			let node = document.getElementById("email-text");
			let sel = window.getSelection();
			sel.selectAllChildren(node);
			document.execCommand("copy");
		}
		
		window.location = "mailto:jubao@12377.cn?subject=" + subject;
	});

	$("#sendemail-copy-send-comp").click(function() {
		if (!checkDescription()) {
			return;
		}
		
		// 复制文本内容;
		let node = document.getElementById("email-text");
		let sel = window.getSelection();
		sel.selectAllChildren(node);
		document.execCommand("copy");
		
		window.location = "mailto:jubao@12377.cn";
	});
	
	$("#sendemail-clear").click(function() {
		chrome.storage.local.remove("capture");
	});

	$("#sendemail-save-screenshot").click(function() {
		let dataURI = $("#email-screenshot").attr("src");
		let blob = dataURItoBlob(dataURI);
		saveAs(blob, _jsonData.guid + ".png");
	});
});
